#include "compiler.h"
#include <stdarg.h>
#include <stdlib.h>

struct lex_process_functions compile_lex_functions = {
    .next_char = compile_process_next_char,
    .peek_char = compile_process_peek_char,
    .push_char = compile_process_push_char};

void compile_error(struct compile_process *compiler, const char *msg, ...)
{
    va_list args;
    va_start(args, msg);
    vfprintf(stderr, msg, args);
    va_end(args);
    fprintf(stderr, "错误！！在%s文件中第%i行，第%i列\n", compiler->pos.filename, compiler->pos.line, compiler->pos.col);
    exit(-1);
}

void compile_warning(struct compile_process *compiler, const char *msg, ...)
{
    va_list args;
    va_start(args, msg);
    vfprintf(stderr, msg, args);
    va_end(args);
    fprintf(stderr, "警告！！在%s文件中第%i行，第%i列\n", compiler->pos.filename, compiler->pos.line, compiler->pos.col);
}

int compile_file(const char *filename, const char *out_filename, int flags)
{
    // 构造编译过程
    struct compile_process *process = compile_process_create(filename, out_filename, flags);

    if (!process)
    {
        return COMPILER_FAILED_WITH_ERRORS;
    }

    // 词法分析 TODO
    printf("词法分析\n");
    struct lex_process *lex_process = lex_process_create(process, &compile_lex_functions, NULL);
    if (!lex_process) // 创建失败
    {
        return COMPILER_FAILED_WITH_ERRORS;
    }
    // 词法分析错误
    if (lex(lex_process) != LEXICAL_ANALYSIS_ALL_OK)
    {
        return COMPILER_FAILED_WITH_ERRORS;
    }
    // 语法分析 TODO
    printf("语法分析\n");

    // 代码生成 TODO
    printf("代码生成\n");

    return COMPILER_FILE_COMPILED_OK;
}